<template>
    <div class="avatar-upload">
      <div v-if="avatarUrl">
        <img :src="avatarUrl" alt="头像" class="avatar-preview" />
      </div>
      <div v-else>
        <p>当前没有头像，请上传一个头像。</p>
      </div>
      <div class="controls">
        <input type="file" @change="onFileChange" />
        <button @click="uploadAvatar" :disabled="!selectedFile">上传</button>
        <button @click="downloadAvatar" :disabled="!avatarUrl">下载</button>
      </div>
    </div>
  </template>
  
  <script>
  import axios from 'axios';
  
  export default {
    data() {
      return {
        selectedFile: null,
        avatarUrl: '', // 存储上传后的头像URL
      };
    },
    methods: {
      onFileChange(event) {
        const file = event.target.files[0];
        this.selectedFile = file;
        if (file) {
          // 生成头像的预览URL
          this.avatarUrl = URL.createObjectURL(file);
        }
      },
      async uploadAvatar() {
        if (!this.selectedFile) return;
  
        const formData = new FormData();
        formData.append('avatar', this.selectedFile);
  
        try {
          const response = await axios.post('/api/upload-avatar', formData, {
            headers: {
              'Content-Type': 'multipart/form-data',
            },
          });
  
          // 假设服务器返回上传后的图片URL
          this.avatarUrl = response.data.avatarUrl;
        } catch (error) {
          console.error('上传失败:', error);
        }
      },
      downloadAvatar() {
        if (!this.avatarUrl) return;
  
        // 创建一个链接元素来触发下载
        const link = document.createElement('a');
        link.href = this.avatarUrl;
        link.download = 'avatar.png'; // 你可以根据需要设置文件名
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      },
    },
    mounted() {
      // 这里你可以从服务器获取当前头像的 URL
      // this.avatarUrl = '服务器返回的头像URL';
    },
  };
  </script>
  
  <style scoped>
  .avatar-upload {
    max-width: 300px;
    margin: 0 auto;
    text-align: center;
  }
  
  .avatar-preview {
    width: 100px;
    height: 100px;
    border-radius: 50%;
    margin-bottom: 20px;
  }
  
  .controls {
    margin-top: 20px;
  }
  
  button {
    margin: 5px;
  }
  </style>
  